package com.baizhiedu.rsm.service.impl;


import com.baizhiedu.rsm.dao.SubjectDao;
import com.baizhiedu.rsm.entity.StudentMessage;
import com.baizhiedu.rsm.entity.Subject;
import com.baizhiedu.rsm.service.SubjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @author lby
 */
@Service
public class SubjectServiceImpl implements SubjectService {
    @Autowired
    private SubjectDao subjectDao;


    @Override
    public int addSubject(Subject subject) {
        return subjectDao.insert(subject);
    }

    @Override
    public List<Subject> showSubjectBySid(Integer frontId,Integer lastId) {
        List<Subject> subjects = null;

        if(frontId<=lastId){
            List<Subject> subjects1 = subjectDao.selectAllBySid(frontId, lastId);
            if(subjects1 == null || subjects1.size()<3){
                subjects = subjectDao.selectAllBySid(1,lastId);
            }
        }else {
            subjects = subjectDao.selectAllBySid(1,frontId);
            if(subjects == null || subjects.size()==0){
                subjects = subjectDao.selectAllBySid(1,10);
            }
        }


        if(subjects== null || subjects.size()==0){
            subjects = subjectDao.selectAllBySid(1,10);
        }

//        随机3道
        List<Subject> subjects2 = new ArrayList<>();
        Random random = new Random();
        for (int i=1;i<=3;i++){
            int i1 = random.nextInt(subjects.size() - 1);
            subjects2.add(subjects.get(i1));
        }

        System.out.println(subjects.size()+"----------------");
        return subjects2;
    }

    @Override
    public List<Subject> showAllSubject() {
        return subjectDao.selectAll();
    }

    @Override
    public Map deleteSelect(List<Subject> subjects) {
        Map map = new HashMap(1);
        try{
            for (Subject s:subjects) {
                Integer id = s.getSbid();
                //在原表中删除
                subjectDao.deleteByPrimaryKey(id);
            }
            map.put("deleteSelect",true);
        }catch (Exception e){
            map.put("deleteSelect",false);
        }
        return map;
    }

    @Override
    public Map updateOne(Subject subject) {
        Map map = new HashMap(1);
        try{
            subjectDao.updateByPrimaryKey(subject);
            map.put("update",true);
        }catch (Exception e){
            map.put("update",false);
        }
        return map;
    }
}
